package com.sip.stream.helper;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Build;
import android.util.Log;
import com.sip.stream.ClientApp;
import com.sip.stream.rxbus.RxBus;

public class PCMStreamPlayer {
    public static final String TAG = "PCMStreamPlayer";
    private AudioTrack audioTrack;
    private int channelCount;
    private int minBufferSize;
    private int sampleRate;
    private AudioFocusRequest audioFocusRequest = null;
    private AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = null;

    public PCMStreamPlayer(int sampleRate, int channelCount) {
        this.sampleRate = sampleRate;
        this.channelCount = channelCount;
        startPlay();
    }

    private void startPlay() {
        this.minBufferSize = AudioTrack.getMinBufferSize(this.sampleRate, this.channelCount == 2 ? 12 : 4, 2);
        //1:    new AudioAttributes.Builder().build();
        //2：   new AudioAttributes.Builder().setLegacyStreamType(0).setUsage(2).setContentType(1).build();
        AudioAttributes createAudioAttributes = new AudioAttributes.Builder().setLegacyStreamType(0).setUsage(2).setContentType(1).build();
        AudioFormat build = new AudioFormat.Builder().setSampleRate(this.sampleRate).setEncoding(2).setChannelMask(4).build();
        Log.i("audioTest", "audioSource: 2 audioFormat:" + build.toString());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.audioTrack = new AudioTrack.Builder().setBufferSizeInBytes(this.minBufferSize).setAudioAttributes(createAudioAttributes).setAudioFormat(build).setTransferMode(1).setSessionId(0).build();
        }
        Log.i(TAG, "new AudioTrack");
        AudioManager audioManager = (AudioManager) ClientApp.clientApp.getSystemService(Context.AUDIO_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {
            this.audioFocusRequest = new AudioFocusRequest.Builder(1).setAcceptsDelayedFocusGain(false).setOnAudioFocusChangeListener(getAudioFocusChangeListener()).setAudioAttributes(createAudioAttributes).build();
            audioManager.requestAudioFocus(this.audioFocusRequest);
        } else {
            audioManager.requestAudioFocus(getAudioFocusChangeListener(), 0, 1);
        }
        if (this.audioTrack.getState() == 0) {
            Log.i(TAG, " audioTrack.getState() == AudioTrack.STATE_UNINITIALIZED");
            return;
        }
        Log.i("audioTest", " audioTrack.play()");
        this.audioTrack.play();
        RxBus.getDefault().unregister(this);
    }

    public void receiveAudioStream(byte[] bArr, long j) {
        AudioTrack audioTrack = this.audioTrack;
        if (audioTrack != null) {
            audioTrack.write(bArr, 0, bArr.length);
        }
    }

    private AudioManager.OnAudioFocusChangeListener getAudioFocusChangeListener() {
        if (this.onAudioFocusChangeListener == null) {
            this.onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
                @Override
                public void onAudioFocusChange(int type) {
                    if (type == -3) {
                        Log.d(PCMStreamPlayer.TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    } else if (type == -2) {
                        PCMStreamPlayer.this.stop();
                        Log.d(PCMStreamPlayer.TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
                    } else if (type == -1) {
                        Log.d(PCMStreamPlayer.TAG, "AUDIOFOCUS_LOSS");
                    } else if (type != 1) {
                    } else {
                        Log.d(PCMStreamPlayer.TAG, "AUDIOFOCUS_GAIN");
                    }
                }
            };
        }
        return this.onAudioFocusChangeListener;
    }

    public void stop() {
        Log.i(TAG, "audioTrack stop");
        RxBus.getDefault().unregister(this);
        if (this.audioFocusRequest != null) {
            AudioManager audioManager = (AudioManager) ClientApp.clientApp.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            if (Build.VERSION.SDK_INT >= 26) {
                audioManager.abandonAudioFocusRequest(this.audioFocusRequest);
            }
            this.audioFocusRequest = null;
            this.onAudioFocusChangeListener = null;
        } else if (this.onAudioFocusChangeListener != null) {
            ((AudioManager)ClientApp.clientApp.getApplicationContext().getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(this.onAudioFocusChangeListener);
        }
        AudioTrack audioTrack = this.audioTrack;
        if (audioTrack == null || audioTrack == null || audioTrack.getState() == 1) {
            return;
        }
        try {
            Log.i(TAG, "audioTrack stop");
            this.audioTrack.stop();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "audioTrack release");
        this.audioTrack.release();
        this.audioTrack = null;
    }

    public int getMinBufferSize() {
        return this.minBufferSize;
    }
}
